﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

/// <summary>
/// WebPartZone Adapter
/// </summary>

namespace Mathoms.iSharePoint
{
    public class WebPartZoneAdapter : System.Web.UI.Adapters.ControlAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            bool inEditMode = false;
            Microsoft.SharePoint.WebPartPages.WebPartZone wpz = Control as Microsoft.SharePoint.WebPartPages.WebPartZone;
            if (wpz != null)
            {
                SPWebPartManager swpm = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(wpz.Page);

                inEditMode = swpm.DisplayMode != System.Web.UI.WebControls.WebParts.WebPartManager.BrowseDisplayMode && wpz.AllowPersonalization == true;
            }
            else
            {
                base.Render(writer);
                return;
            }

            // MasterPageFile == '/_catalogs/masterpage/iSharePoint.master'
            if (null == wpz.Page.MasterPageFile || !wpz.Page.MasterPageFile.Contains(@"/iSharePoint"))
            {
                base.Render(writer);
                return;
            }
            else
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "mis-wpZone");
                writer.AddAttribute("zoneId", wpz.ID);
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Indent++;

                if (wpz.WebParts.Count == 0)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Table);
                    writer.Indent++;
                    writer.RenderBeginTag(HtmlTextWriterTag.Tbody);
                    writer.Indent++;
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "s4-wpcell-plain");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.Write("&nbsp;");
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                    writer.RenderEndTag();
                }
                else
                {
                    base.Render(writer);
                    writer.Indent--;
                }
                writer.RenderEndTag(); // </DIV>
            }
        }
    }
}
